package com.deanlib.cabinet.ui.adapter;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.HttpMethod;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestFutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.deanlib.cabinet.R;
import com.deanlib.cabinet.data.AppDatabase;
import com.deanlib.cabinet.data.model.Resource;
import com.deanlib.cabinet.data.model.ResourceCache;
import com.deanlib.cabinet.databinding.LayoutMediaContentItemBinding;
import com.deanlib.cabinet.ui.recyclerview.CommonRecyclerViewAdapter;
import com.deanlib.cabinet.ui.recyclerview.CommonViewHolder;
import com.deanlib.cabinet.utils.ConfigManager;
import com.deanlib.cabinet.utils.FileUtilsExt;
import com.deanlib.cabinet.utils.MediaUtilsExt;
import com.deanlib.cabinet.utils.OssManager;
import com.deanlib.plantern.utils.FileUtils;
import com.deanlib.plantern.utils.FormatUtils;
import com.deanlib.plantern.utils.ImageUtils;
import com.deanlib.plantern.utils.PopupUtils;
import com.elvishew.xlog.XLog;

import java.io.File;
import java.util.List;
import java.util.Optional;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MediaGrid2Adapter extends CommonRecyclerViewAdapter<LayoutMediaContentItemBinding> {

    private List<Resource> mDataList;

    public MediaGrid2Adapter(List<Resource> dataList) {
        super(R.layout.layout_media_content_item);
        mDataList = dataList;
    }

    @NonNull
    @Override
    public CommonViewHolder<LayoutMediaContentItemBinding> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        CommonViewHolder<LayoutMediaContentItemBinding> holder =
                new CommonViewHolder<>(LayoutInflater.from(parent.getContext()).inflate(layout, parent, false));
        holder.setIsRecyclable(false);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull CommonViewHolder<LayoutMediaContentItemBinding> holder, int position) {
        super.onBindViewHolder(holder, position);
        Resource resource = mDataList.get(position);
        if (resource != null) {
            //优化了加载方式，滑动停止加载，PhotoList3Fragment#binding.rvResources.addOnScrollListener
            loadItem(holder, resource);

            if (FileUtilsExt.isVideo(resource.mineType)) {
                holder.binding.imgPlay.setVisibility(View.VISIBLE);
                holder.binding.tvDuration.setVisibility(View.VISIBLE);
                String duration = FormatUtils.convertTimestampToDuration(resource.duration * 1000);
                if (duration.startsWith("00:")) {
                    duration = duration.substring(3);
                }
                holder.binding.tvDuration.setText(duration);
            } else {
                holder.binding.imgPlay.setVisibility(View.GONE);
                holder.binding.tvDuration.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(resource.localPath) && !Optional.ofNullable(resource.synced).orElse(false)) {
                holder.binding.imgSyncState.setVisibility(View.VISIBLE);
                holder.binding.imgSyncState.setOnClickListener(view -> {
                    //todo 加入上传队列，且优先级最高
                });
            } else {
                holder.binding.imgSyncState.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public void loadItem(CommonViewHolder<LayoutMediaContentItemBinding> holder, Resource resource){
        if (resource != null) {
            String url = resource.localThumbnail;
            if (TextUtils.isEmpty(url)) {
                url = resource.localPath;
            }
            if (!TextUtils.isEmpty(url)) {
                //本地资源加载
                Glide.with(holder.binding.imgPhoto.getContext()).load(url)
                        .apply(RequestOptions.placeholderOf(R.drawable.placeholer).error(R.drawable.error))
                        .into(holder.binding.imgPhoto);
            } else {
                //没有本地资源 从网络加载
                holder.binding.imgPhoto.setImageResource(R.drawable.placeholer);
                String objPath = resource.thumbnail;
                if (TextUtils.isEmpty(objPath)) {
                    objPath = resource.path;
                }
                if (!TextUtils.isEmpty(objPath)) {
                    //由于数据结构的变化，存于OSS上的数据资源的名称之前用的压缩后md5值，现在用的是压缩前md5值命名
                    //所以在 GetObjectRequest 的第二个参数生成里，需要注意
                    String md5 = resource.md5;
                    if (!objPath.contains(resource.md5)) {
                        md5 = resource.newMd5;
                    }
                    if (!TextUtils.isEmpty(resource.thumbnail) || FileUtilsExt.isImage(resource.mineType)) {
                        //如果视频封面不空或是图片，直接下载缓存再展示
                        //下载方式
                        GetObjectRequest request = new GetObjectRequest(
                                ConfigManager.getInstance().getOssKey().extend2,
                                OssManager.createObjKey(md5, objPath.substring(objPath.lastIndexOf("."))));
//                      String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
                        String style = "image/resize,w_400"; //todo 可以按屏幕分辨率做调整
                        request.setxOssProcess(style);
                        OssManager.getInstance().getOssClient().asyncGetObject(request, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
                            @Override
                            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                                String outFilePath = ResourceCache.createCacheThumbnailPath(resource.md5);
                                if (FileUtilsExt.saveFileByStream(result.getObjectContent(), outFilePath)) {
                                    MediaUtilsExt.loadThumbnail(resource, outFilePath, holder.binding.imgPhoto);
                                } else {
                                    holder.binding.imgPhoto.setImageResource(R.drawable.error);
                                }
                            }

                            @Override
                            public void onFailure(GetObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                clientException.printStackTrace();
                                serviceException.printStackTrace();
                                holder.binding.imgPhoto.setImageResource(R.drawable.error);
                            }
                        });
                    } else if (FileUtilsExt.isVideo(resource.mineType)) {
                        //这种方式加载视频会影响到其他图片的加载，而且有部分视频加载失败无法获取截图
                        //没有封面的视频 使用 签名url的方式 尝试用glide加载第一帧
                        //签名URL方式
//                                        try {
//                                            String finalMd5 = md5;
//                                            addDisposable(Observable.create((ObservableOnSubscribe<String>) emitter -> {
//                                                        try {
//                                                            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
//                                                                    ConfigManager.getInstance().getOssKey().extend2,
//                                                                    OssManager.createObjKey(finalMd5, resource.path.substring(resource.path.lastIndexOf("."))));
//                                                            // 设置签名URL的过期时间，单位秒
//                                                            request.setExpiration(10 * 60);
//                                                            request.setMethod(HttpMethod.GET);
//                                                            String path = OssManager.getInstance().getOssClient().presignConstrainedObjectURL(request);
//                                                            emitter.onNext(path);
//                                                        } catch (Exception e) {
//                                                            e.printStackTrace();
//                                                            emitter.onError(e);
//                                                        }
//
//                                                    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                                                    .subscribe(path -> {
//                                                        Glide.with(holder.binding.imgPhoto.getContext()).asBitmap().load(path)
//                                                                .apply(RequestOptions
//                                                                        .placeholderOf(R.drawable.placeholer)
//                                                                        .error(R.drawable.error)
//                                                                        .frame(0))
//                                                                .into(new CustomTarget<Bitmap>() {
//                                                                    @Override
//                                                                    public void onResourceReady(@NonNull Bitmap res, @Nullable Transition<? super Bitmap> transition) {
//                                                                        File outFile = new File(ResourceCache.createCacheThumbnailPath(resource.md5));
//                                                                        ImageUtils.saveBitmap(res, outFile.getParentFile(), outFile.getName(), new FileUtils.FileCallback() {
//                                                                            @Override
//                                                                            public void onSuccess(File file) {
//                                                                                MediaUtilsExt.loadThumbnail(resource, file.getPath(), holder.binding.imgPhoto, false);
//                                                                            }
//
//                                                                            @Override
//                                                                            public void onFail(Exception e) {
//                                                                                e.printStackTrace();
//                                                                            }
//                                                                        });
//                                                                    }
//
//                                                                    @Override
//                                                                    public void onLoadCleared(@Nullable Drawable placeholder) {
//
//                                                                    }
//                                                                });
//                                                    }));
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
                    }
                }
            }
        }
    }
}
